import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { BusinessCircleService } from '../business-circle.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common'; 
import { PermissionService } from '../../../service/permission.service';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

@Component({
  selector: 'app-posts-manage',
  templateUrl: './posts-manage.component.html',
  styleUrls: ['./posts-manage.component.scss'],
  providers: [DatePipe]
})
export class PostsManageComponent implements OnInit {

  isCollapse: boolean = false;
  // seachForm
  seachParams: any = {
    user: '', // 用户
    title: '', // 帖子标题
    boardId: '', // 板块
    boardTypeId: '', // 类型
    identity: '', // 发布身份
    status: '', // 帖子状态
    issueStatus: '', // 问题状态
    beginTime: '', // 创建开始时间
    endTime: '', // 创建结束时间
    beginReleaseTime: '', // 发表开始时间
    endReleaseTime: '' // 发表结束时间
  };
  sortParams: any = {
    sortField: '',
    sort: '' // 0表示正序 1表示倒序
  };
  // 创建日期
  establishDates: any = [];
  // 发表日期
  publishDates: any = [];
  // 板块下拉
  plateOptions: any = [];
  // 帖子类型下拉
  postTypeOptions: any = [];

  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  // 表格data
  tableData: any = [];

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private datePipe: DatePipe,
    private services: BusinessCircleService,
    public permission: PermissionService,
  ) { }

  ngOnInit(): void {
    this.queryPlateList();
    this.queryPostTypeList();
    this.loadTable();
  }

  // 查询板块下拉
  async queryPlateList() {
    try {
      const res: any = await this.services.getCircleTableData();
      if (res.code == 0) {
        this.plateOptions = res.data || [];
      }
    } catch (error) {
      this.plateOptions = [];
    }
  }
  // 查询帖子类型
  async queryPostTypeList() {
    try {
      const res: any = await this.services.getPostsTypeTableData({boardId: this.seachParams.boardId});
      if (res.code == 0) {
        this.postTypeOptions = res.data || [];
      }
    } catch (error) {
      this.postTypeOptions = [];
    }
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        ...this.sortParams,
        page: this.tableForms.page,
        pageSize: this.tableForms.pageSize
      }

      this.tableForms.tableLoading = true;
      const res: any = await this.services.queryPostsListData(params);
      this.tableForms.tableLoading = false;
      if (res.code == 0) {
        const { records, total }: any = res.data;
        this.tableData = records || [];
        this.tableForms.total = total || 0;
      }
    } catch (error) {
      this.tableForms.tableLoading = false;
      this.tableData = [];
      this.tableForms.total = 0;
    }
  }
  queryData() {
    console.log('seach params', this.seachParams);
    this.tableForms.page = 1;
    this.loadTable();
  }
  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.establishDates = [];
    this.publishDates = [];

    this.tableForms.page = 1;
    this.loadTable();
  }

  onQueryParamsChange(params: NzTableQueryParams) {
    console.log('排序', params);
    const { pageSize, pageIndex, sort, filter } = params;
    const currentSort = sort.find(item => item.value !== null);
    const sortField = (currentSort && currentSort.key) || null;
    const sortOrder = (currentSort && currentSort.value) || null;
    // 0表示正序 1表示倒序
    if (sortOrder) {
      this.sortParams.sortField = sortField;
      this.sortParams.sort = sortOrder == 'ascend' ? '0' : '1';
    } else {
      this.sortParams.sortField = '';
      this.sortParams.sort = '';
    }
    this.loadTable();
  }

  // 发表时间change
  onChange(result: Date[], num: number) {
    console.log('onChange: ', result, num);
    switch (num) {
      case 0:
        this.seachParams.beginTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
        this.seachParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
        break;
      case 1:
        this.seachParams.beginReleaseTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
        this.seachParams.endReleaseTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
        break;
    }
  }

  /**
   * 操作
   * @param item 
   * @param num 0：置顶，1：下架，2：删除
   */
  modifyData(item: any, num: number) {
    switch (num) {
      case 0:
        console.log('置顶');
        this.updateToppingItem({id: item.id, topFlag: item.topFlag == 0 ? 1 : 0});
        break;
      case 1:
        console.log('下架');
        this.updateToppingItem({id: item.id, status: 2});
        break;
      case 2:
        console.log('删除');
        this.deletePostsItemData(item);
        break;
    }
  }

  // 是否置顶 (0默认、1置顶 | 下架)
  async updateToppingItem(params: any) {
    try {
      const res: any = await this.services.updatePostsItemData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }
  // 删除帖子
  async deletePostsItemData(item: any) {
    try {
      const res: any = await this.services.deletePostsData({id: item.id});
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 板块下拉change
  boardChange(ev: any) {
    this.seachParams.boardTypeId = '';
    this.queryPostTypeList();
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }

  // 板块文字转化
  plateTextTransform(boardId: any) {
    let tempObj = this.plateOptions.find((item: any) => item.id == boardId);
    return tempObj.boardName || '-';
  }
  // 类型文字转化
  postTypeTextTransform(boardTypeId: any) {
    let tempObj = this.postTypeOptions.find((item: any) => item.id == boardTypeId);
    return tempObj.typeName || '-';
  }
}
